package com.mj;

public class ArrayList<E> {
	private int size;
	private E[] elements;

	private static final int DEFAULT_CAPACITY = 2;
	private static final int ELEMENT_NOT_FOUND = -1;

	public ArrayList(int capaticy) {
		capaticy = capaticy < DEFAULT_CAPACITY ? DEFAULT_CAPACITY : capaticy;
		elements = (E[]) new Object[capaticy];
	}
	
	public boolean isEmpty() {
		 return size == 0;
	}

	public int size() {
		return size;
	}

	public void add(E element) {
		add(size, element);
	}

	public void add(int index, E element) {
		rangeCheckForAdd(index);
		ensureCapacity(index + 1);
		for (int i = size; i > index; i--) {
			elements[i] = elements[i - 1];
		}
		elements[index] = element;
		size++;
	}

	public E remove(int index) {
		rangeCheck(index);
		E oldElement = elements[index];
		for (int i = index + 1; i < size; i++) {
			elements[i - 1] = elements[i];
		}
		elements[--size] = null;
		return oldElement;
	}
	
	public void clear() {
		for (int i = 0; i < size; i++) {
			elements[i] = null;
		}
		size = 0;
	}
	
	public E get(int index) { // O(1)
		rangeCheck(index);
		
		return elements[index]; 
	}

	
	public int indexof(E element) {
		if (element == null) {
			for (int i = 0; i < size; i++) {
				if (elements[i] == null) { return i; }
			}
		}else {
			for (int i = 0; i < size; i++) {
				if (elements[i].equals(element)) return i;				
			}
		}
		return ELEMENT_NOT_FOUND;
	}

	private void ensureCapacity(int capacity) {
		int oldcapacity = elements.length;
		if (oldcapacity >= capacity)
			return;
		int newCapacity = oldcapacity + (oldcapacity >> 1);
		E[] newElements = (E[]) new Object[newCapacity];
		for (int i = 0; i < elements.length; i++) {
			newElements[i] = elements[i];
		}
		elements = newElements;
		System.out.println(oldcapacity + "扩容为" + newCapacity);
	}

	private void rangeCheck(int index) {
		if (index < 0 || index >= size) {
			outOfBounds(index);
		}
	}

	private void rangeCheckForAdd(int index) {
		if (index < 0 || index > size) {
			outOfBounds(index);
		}
	}

	private void outOfBounds(int index) {
		throw new IndexOutOfBoundsException("Index:" + index + ", Size:" + size);
	}

	@Override
	public String toString() {
		// size=3, [99, 88, 77]
		StringBuilder string = new StringBuilder();
		string.append("size=").append(size).append(", [");
		for (int i = 0; i < size; i++) {
			if (i != 0) {
				string.append(", ");
			}
			string.append(elements[i]);
		}
		string.append("]");
		return string.toString();
	}
}
